<template>
  <page-loading
    :loading.sync="pageLoading"
    :error.sync="pageError"
    :enable-pull-refresh="false"
    @reload="getData"
  >
    <template v-if="hasVoteInfo">
    <div class="vote">
      <div class="head">
        <div class="col">
          <div class="vote-title">{{ voteInfo.title }}</div>
          <div class="vote-creator" @click="toSpace(voteInfo.uid)">
            <user-avatar
              class="avatar"
              size="sm"
              :url="voteInfo.face"
              :vip-status="-1"
            />
            <span class="user-name">{{ voteInfo.name }}</span>
            <span class="user-text">发起</span>
            <span class="user-text" v-if="voting">{{ voteInfo.endtime | leftTime }}</span>
          </div>
        </div>
        <div class="vote-number van-hairline--surround">
          <span class="num">{{ voteInfo.cnt }}</span>
          <span class="text">参与人数</span>
        </div>
      </div>
      <div class="body">
        <div class="options-head">
          <span class="options-title">投票选项</span>
          <span class="choice-count">最多选{{voteInfo.choice_cnt}}项</span>
        </div>
        <!--:max="voteInfo.choice_cnt"-->
        <van-checkbox-group v-model="voteResult" ref="checkboxGroup">
          <ul class="options-list">
            <li
              v-for="(item, index) in voteInfo.options"
              :key="item.idx"
              :class="{max: maxCnt === item.cnt}"
              @click="toggleCheckbox(index)"
            >
              <div class="option-content">
                <div v-if="!voting" class="precentage-bar" :style="{ width: item.percentage }"></div>
                <div class="vote-desc">
                  <div class="option-text">{{ item.desc }}</div>
                  <div v-if="!voting" class="vote-count">{{ item.cnt }}票</div>
                </div>
                <div v-if="!voting" class="vote-percentage">{{ item.percentage }}</div>
                <div v-if="voting" class="vote-checkbox">
                  <van-checkbox ref="checkboxes" :name="item.idx" :checked-color="rootThemeColor"></van-checkbox>
                </div>
              </div>
            </li>
          </ul>
        </van-checkbox-group>
        <div class="button-wrap">
          <van-button v-if="voting" :color="hasVoteResult ? rootThemeColor : voteBtnDisabledColor" @click="handleVote" block size="large">投票</van-button>
          <van-button v-else :color="voteBtnDisabledColor" block disabled size="large" class="vbutton">投票已结束</van-button>
        </div>
      </div>
      <div class="foot van-hairline--top">
        <refresh-list
          ref="refreshList"      
          :enable-pull-refresh="false"
          @pull-load="onListLoad"
        >
          <vote-comment
            :comments="voteComments"
            :show-loading="false"
          />

        </refresh-list>
      </div>
    </div>
    </template>
  </page-loading>
</template>

<script>
import { 
  Button as VanButton, 
  CheckboxGroup as VanCheckboxGroup, 
  Checkbox as VanCheckbox
} from 'vant'
import RefreshList from '@/components/refresh-list/RefreshList'
import UserAvatar from '@/components/user-avatar/UserAvatar'
import PageLoading from '@/components/page-loading/PageLoading'
import pageLoadingMixin from '@/mixins/pageLoading'
import VoteComment from '@/components/comment/Comment'
import { apiGetInfo, apiGetComments } from '@/api/vote'
export default {
  name: 'Vote',
  mixins: [pageLoadingMixin],
  inject: ['rootThemeColor', 'rootTitle'],
  metaInfo () {
    return {
      title: this.title
    }
  },
  components: {
    PageLoading,
    UserAvatar,
    VanButton,
    VanCheckboxGroup,
    VanCheckbox,
    VoteComment,
    RefreshList
  },
  props: {
    vid: {
      type: [Number, String]
    }
  },
  data () {
    return {
      voteInfo: null,
      voteResult: [],
      voteComments: [],
      next: null,
      maxCnt: null,
      voteBtnDisabledColor: '#e5e9ef'
    }
  },
  computed: {
    title () {
      let word = this.rootTitle
      if (this.hasVoteInfo) {
        word = `投票-${this.voteInfo.title}_${word}`
      }
      return word
    },
    voteId () {
      return this.vid
    },
    voting () {
      let flag = false
      if (this.hasVoteInfo) {
        flag = this.voteInfo.endtime * 1000 > new Date().getTime()
      }
      return flag
    },
    hasVoteInfo () {
      return this.voteInfo !== null
    },
    hasVoteResult () {
      return this.voteResult.length
    }
  },
  watch: {
    vid (newVal) {
      this.getData()
    }
  },
  filters: {
    leftTime (value) {
      const endtime = value * 1000
      const nowtime = new Date().getTime()
      const left = endtime - nowtime
      if (left >= 0) {
        const leftDay = Number.parseInt(left / (24 * 60 * 60 * 1000))
        const leavel = left % (24 * 3600 * 1000)
        const leftHours = Math.floor(leavel / (3600 * 1000))
        const leavel2 = leavel % (3600 * 1000)
        const leftMinutes = Math.floor(leavel2 / (60 * 1000))
        return `剩余${leftDay}天${leftHours}时${leftMinutes}分`
      }
    }
  },
  created () {
    this.getData()
  },
  methods: {
    getData () {
      apiGetInfo({ id: this.voteId }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { info, info: { cnt, options, uid } } = data
          if (uid === 0) {
            this.$router.replace({ name: '404' })
          }
          const cnts = []
          options.forEach(option => {
            if (option.cnt) {
              cnts.push(option.cnt)
              option.percentage = (option.cnt / cnt * 100).toFixed(2) + '%'
            } else {
              option.percentage = '0.00%'
            }
          })
          if (cnts.length) {
            this.maxCnt = Math.max(...cnts)
          }
          this.voteInfo = info
        } else {
          this.pageError = true
        }
      }).then(() => {
        this.getComments()
      }).catch(err => {
        console.log(err)
        this.pageError = true
      }).finally(() => {
        this.pageLoading = false
      })
    },
    getComments () {

      apiGetComments({ id: this.voteId, mode: 3, next: this.next }).then(res => {
        const { code, data } = res
        if (code === 0 && data) {
          const { replies, cursor, cursor: { next } } = data
          this.next = next          
          if (cursor.is_end) {
            this.$refs.refreshList.completeLoad()
          } else {
            this.voteComments.push(...replies)
          }
        } else {
          this.$refs.refreshList.completeLoad()
        }
      }).catch(err => {
        console.log(err)
        this.$refs.refreshList.showError()
      }).finally(() => {
        this.$refs.refreshList.stopLoad()
        this.$refs.refreshList.stopRefresh()
      })

    },
    onListLoad () {
      clearTimeout(this.listTimeout)
      if (!this.listFinished) {
        this.listTimeout = setTimeout(() => {
          this.getComments()
        }, 1000)
      }
    },
    toSpace (mid) {
      this.$router.push({ name: 'space', params: { mid } })
    },
    toggleCheckbox (curIndex) {
      if (this.voteInfo.choice_cnt === 1) {
        this.$refs.checkboxGroup.toggleAll(false)
      }
      this.$refs.checkboxes[curIndex].toggle()
    },
    // 处理投票逻辑
    handleVote () {
      // TODO: 处理投票逻辑 需要登录状态判断
    }
  }
}
</script>

<style lang="scss" scoped>
  .vote{
    padding: {
      left: 10px;
      right: 10px;
      top: 10px;
    };
    .head{
      display: flex;
      align-items: center;
      margin: {
        top: 12px;
        bottom: 34px;
      }
      color: $color-text-regular;
      .col {
        flex: 1;
      }
    }
    .foot{
      padding-top: 20px;
    }
    &-title{
      margin: {
        right: 12px;
        bottom: 12px;
      };
      font: {
        size: 20px;
        weight: 700;
      }
      color: $color-text-primary;
    }
    &-creator {
      display: flex;
      align-items: center;
      font-size: 12px;
      .avatar{
        width: 28px;
        height: 28px;
        margin-right: 8px;
      }
      .user-name,.user-text{
        margin-right: 4px;
      }
      .user-name{
        color: $color-text-regular;
      }
      .user-text{
        color: $color-text-secondary;
      }
    }
    &-number{
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
      width: 76px;
      height: 76px;
      @include border1px(#e7e7e7, 1px, 50%);
      font-size: 10px;
      .num {
        color: $theme-color;
        font-size: 18px;
      }
    }
    .options-head{
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-bottom: 12px;
    }
    .options-title{
      font: {
        size: 16px;
        weight: 700;
      }
      color: $color-text-primary;
    }
    .choice-count{
      font-size: 13px;
      color: $color-text-secondary;
    }
    .options-list{
      margin-bottom: 18px;
      li{
        position: relative;
        display: flex;
        margin-bottom: 10px;
        @include border1px(#dcdcdc, 1px, 4px);
        cursor: pointer;
        overflow: hidden;
      }
    }
    .option-content{
      position: relative;
      display: flex;
      flex: 1;
      justify-content: space-between;
      align-items: center;
      min-height: 44px;
      padding: 4px 13px;
    }
    .precentage-bar{
      height: 100%;
      position: absolute;
      top: 0;
      left: 0;
      background-color: rgba(232,237,244, .9);
    }
    .vote-desc{
      font-size: 14px;
      color: $color-text-primary;
      -webkit-box-ordinal-group: 0;
      order: -1;
      z-index: 2;
    }
    .vote-count{
      font-size: 10px;
    }
    .vote-percentage{
      color: $color-text-regular;
      font-size: 14px;
    }
    .options-list li.max{
      .precentage-bar{
        background-color: #fad4df
      }
      .vote-percentage{
        font-weight: 700;
      }
    }
  }
  .vbutton{
    color: #b8c0cc;
  }
  .button-wrap{
    padding-top: 14px;
    margin-bottom: 20px;
  }
</style>
